package com.knight.hadoop.day10.inver.index;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 实现倒排索引，内容类似于类目录下的txt的文件内容
 * 
 * a.txt的内容： hello tom hello jerry hello tom
 * 
 * b.txt的内容 hello jerry hello jerry tom jerry
 * 
 * c.txt内容 hello jerry hello tom
 * 
 * 最后结果： hello a.txt-3 b.txt-2 c.txt-2 tom a.txt-2 b.txt1 c.txt-1 jerry a.txt-1
 * b.txt-3 c.txt-1
 * 
 * 实现方法： 将单词和文件名作为key，value就是该单词在该文件出现的次数，结果如下： hello-a.txt 3 hello-b.txt 2
 * hello-c.txt 2
 * 
 * 第二步： 将第一步作为输入，使用hello作为key，文件和次数为value，结果如下: hello a.txt 3 b.txt 2 c.txt 2
 * 实现业务需求
 * 
 * 实现第二步：
 * 输入：
 *  hello-a.txt	3
	hello-b.txt	2
	hello-c.txt	2
	jerry-a.txt	1
	jerry-b.txt	3
	jerry-c.txt	1
	tom-a.txt	2
	tom-b.txt	1
	tom-c.txt	1
 * 
 * @author
 *
 */
public class InverIndexStepTwo {

	static class InverIndexStepTwoMapper extends Mapper<LongWritable, Text, Text, Text> {

		Text outPutKey = new Text();
		Text outPutValue = new Text();

		@Override
		protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
			
			String line = value.toString();
			String[] values = line.split("-");
			
			outPutKey.set(values[0]);
			outPutValue.set(values[1]);
			
			context.write(outPutKey, outPutValue);
			
		}
	}

	static class InverIndexStepTwoReducer extends Reducer<Text, Text, Text, Text> {
		
		Text outPutValue = new Text();
		
		@Override
		protected void reduce(Text key, Iterable<Text> values, Context context)
				throws IOException, InterruptedException {
			
			StringBuffer sb = new StringBuffer();
			
			for(Text t:values){
				sb.append(t.toString()+"\t");
			}
			
			outPutValue.set(sb.toString());
			context.write(key, outPutValue);
		}
	}
	
	public static void main(String[] args) throws Exception {
		
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		job.setJarByClass(InverIndexStepTwo.class);
		
		//如果mapper的outputkey和最后输出的一样，可以只写最后一个
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		
		job.setMapperClass(InverIndexStepTwoMapper.class);
		job.setReducerClass(InverIndexStepTwoReducer.class);
		
		FileInputFormat.setInputPaths(job, new Path("E:/home/inverIndex/output"));
		FileOutputFormat.setOutputPath(job, new Path("E:/home/inverIndex/outputTwo"));
		
		boolean res = job.waitForCompletion(true);
		System.exit(res?0:1);
	}

}
